package com.rem.chat.websocket;

import com.rem.chat.common.utils.JacksonUtil;
import com.rem.chat.service.dto.MessageSendDTO;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author: Themberfue
 * @date: 2025/6/17 15:12
 * @description:
 */
@Component
public class MessageHandler {
    public static final String MESSAGE_TOPIC = "message.topic";
    private static final Logger log = LoggerFactory.getLogger(MessageHandler.class);

    @Resource
    RedissonClient redissonClient;

    @Resource
    ChannelContextUtil channelContextUtil;

    @PostConstruct
    public void listenMessage() {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.addListener(MessageSendDTO.class, ((charSequence, messageSendDTO) -> {
            log.info("收到广播消息： {}", JacksonUtil.writeValueAsString(messageSendDTO));
            channelContextUtil.sendMessage(messageSendDTO);
        }));
    }

    public void sendMessage(MessageSendDTO<Object> messageSendDTO) {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.publish(messageSendDTO);
    }
}
